package com.rytong.tools.ui;

////#define Android1.0
import java.util.ArrayList;
import java.util.Random;
import com.rytong.tools.utils.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
//#ifdef Android1.0
//#else
import android.view.inputmethod.InputMethodManager;
//#endif

import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

//密码键盘控件
public class LPKeyboardView extends PopupWindow {

    private Context mContext;
    private Button hideButton;
    private Button numButton;
    private LinearLayout linear;
    // 数字，字母随机数组
    private int[] mRandom = new int[10];
    private String[] mRandomStr = new String[26];
    // 字母数字标志位
    private String mNumOrStr;
    private static final String[] littleLetter = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d",
            "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m" };
    private static final String[] capitalLetter = { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D",
            "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M" };

    // 存放真实数值
    // public String real;
    // private StringBuffer realValue = new StringBuffer();
    public ArrayList<LPKeyboardButton> buttonlist = new ArrayList<LPKeyboardButton>();
    // 存放星号
    private StringBuffer passwordValue = new StringBuffer();
    // 密码框
    private LPPasswordText mPasswordText;
    // 可输入密码最大长度
    private int mMaxSize;
    // buttonId
    private int capitalSwitchButton = 1000;
    private int okButton = 1001;
    private int delButton = 1002;

    // #ifdef Android1.0
    // #else
    protected InputMethodManager imm;
    private int height_;

    // #endif

    public LPKeyboardView(Context context, String numOrStr, LPPasswordText passwordText, int maxSize, int dialog_style) {
        super(context);
        this.getBackground().setAlpha(0);
        mContext = context;
        mNumOrStr = numOrStr;
        mPasswordText = passwordText;
        mMaxSize = maxSize;
        initView();
        initKeyboard();
        initKeyboardHeight();
        LayoutInflater inflater = LayoutInflater.from(mContext);
        int keyboard_layout = Utils.getResourcesId(mContext, "keyboard", "layout");
        View view = inflater.inflate(keyboard_layout, null);
//        view.setOnFocusChangeListener(new OnFocusChangeListener() {
//Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                // #ifdef Android1.0
//                // #else
//                imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(mPasswordText.realView_.getWindowToken(), 0);
//                // #endif
//                // 设置dialog位置
//                Window mWindow = LPKeyboardView.this.
//                // 使对话框位于屏幕居下
//                mWindow.setGravity(Gravity.BOTTOM);
//                mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//                WindowManager.LayoutParams params = mWindow.getAttributes();
//                mWindow.setAttributes(params);
//                // LPKeyboardView.this.showAtLocation(ComponentCopy.COMPONENT.getLPView(), Gravity.BOTTOM, 0, 0);
//            }
//        });
    }
    
    private void initKeyboard() {
        linear.removeAllViews();
        if (mNumOrStr.equals("num")) {
            initNumKeyboard();
        } else {
            if (mNumOrStr.equals("ABC")) {
                getRandomCapitalStr();
            } else {
                getRandomlittleStr();
            }
            initStrKeyboard();
        }
    }
    
    public void initKeyboardHeight() {
        height_ = 220;
        try {
            Bitmap keyboardBg = Utils.getBitmapFromResources(mContext, "keyboardbg");
            Bitmap abcBitmap = Utils.getBitmapFromResources(mContext, "abc123");
            height_ = keyboardBg.getHeight()+ abcBitmap.getHeight();
            if (!keyboardBg.isRecycled()) {
                keyboardBg.recycle();
            }
            if (!abcBitmap.isRecycled()) {
                abcBitmap.recycle();
            }
        } catch (Exception e) {
            Utils.printException(e);
        }
    }
    
    public int getHeight() {
        return height_;
    }

    private void initView() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        int keyboard_layout = Utils.getResourcesId(mContext, "keyboard", "layout");
        View view = inflater.inflate(keyboard_layout, null);
        this.setContentView(view);
        // view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        view.setBackgroundDrawable(null);

        int hide_id = Utils.getResourcesId(mContext, "hide", "id");
        hideButton = (Button) view.findViewById(hide_id);
        hideButton.setOnClickListener((android.view.View.OnClickListener) KeyClickListener);
        int numorstr_id = Utils.getResourcesId(mContext, "numorstr", "id");
        numButton = (Button) view.findViewById(numorstr_id);
        numButton.setOnClickListener((android.view.View.OnClickListener) KeyClickListener);
        int relativelayout_id = Utils.getResourcesId(mContext, "relativeLayout", "id");
        RelativeLayout relative = (RelativeLayout) view.findViewById(relativelayout_id);
        int keyboard_id = Utils.getResourcesId(mContext, "keyboard", "id");
        linear = (LinearLayout) view.findViewById(keyboard_id);
        if (mNumOrStr.equalsIgnoreCase("num")) {
            relative.removeView(numButton);
            relative.postInvalidate();
        }
    }

    private void initStrKeyboard() {
        int numCol = 10;
        int numRow = 3;
        int str_style_drawable = Utils.getResourcesId(mContext, "str_style", "drawable");
        int str_up_style_drawable = Utils.getResourcesId(mContext, "str_up_style", "drawable");
        int str_ok_style_drawable = Utils.getResourcesId(mContext, "str_ok_style", "drawable");
        int str_del_style_drawable = Utils.getResourcesId(mContext, "str_del_style", "drawable");
        for (int i = 0; i < numRow; i++) {
            LinearLayout linearlayout = new LinearLayout(mContext);
            linearlayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            for (int j = 0; j < numCol; j++) {
                LPKeyboardButton button = new LPKeyboardButton(mContext, str_style_drawable);
                button.setOnClickListener(KeyClickListener);
                button.setWidth((Component.SCREENWIDTH - Utils.getScaledValueX(10)) / 10);
                button.setHeight(45);
                if (i == 0 || i == 1) {
                    button.setText(String.valueOf(mRandomStr[i * numCol + j]));
                    button.setBackgroundResource(str_style_drawable);
                } else if (i == 2) {
                    if (i == numRow - 1 && j == 0) {
                        // 大小写切换键
                        button.setId(capitalSwitchButton);
                        button.setBackgroundResource(str_up_style_drawable);
                    } else if (i == numRow - 1 && j == numCol - 1) {
                        // OK键
                        button.setId(okButton);
                        button.setText("OK");
                        button.setWidth((Component.SCREENWIDTH - Utils.getScaledValueX(10)) / 10 * 2);
                        button.setBackgroundResource(str_ok_style_drawable);
                    } else if (i == numRow - 1 && j == numCol - 2) {
                        // DEL键
                        button.setId(delButton);
                        button.setBackgroundResource(str_del_style_drawable);
                    } else {
                        if ((i * numCol + j) < 26) {
                            button.setText(String.valueOf(mRandomStr[i * numCol + j + 1]));
                            button.setBackgroundResource(str_style_drawable);
                        }
                    }
                }
                linearlayout.addView(button);
            }
            if (i == 1) {
                numCol = 9;
            }
            linear.setPadding(Utils.getScaledValueX(5), Utils.getScaledValueX(20), Utils.getScaledValueX(5),
                    Utils.getScaledValueX(20));
            linear.addView(linearlayout);
        }
    }

    // 4行3列
    private void initNumKeyboard() {
        getRandomNum();
        int numCol = 4;
        int numRow = 3;
        int str_style_drawable = Utils.getResourcesId(mContext, "str_style", "drawable");
        int num_ok_style_drawable = Utils.getResourcesId(mContext, "num_ok_style", "drawable");
        int num_del_style_drawable = Utils.getResourcesId(mContext, "num_del_style", "drawable");
        int num_style_drawable = Utils.getResourcesId(mContext, "num_style", "drawable");
        for (int i = 0; i < numRow; i++) {
            LinearLayout linearlayout = new LinearLayout(mContext);
            linearlayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            for (int j = 0; j < numCol; j++) {
                LPKeyboardButton button = new LPKeyboardButton(mContext, str_style_drawable);
                button.setTextColor(Color.BLACK);
                button.setTextSize(18);
                button.setWidth((Component.SCREENWIDTH - Utils.getScaledValueX(30)) / numCol);
                button.setOnClickListener((android.view.View.OnClickListener) KeyClickListener);
                if (i == numRow - 1 && j == numCol - 1) {// OK键
                    button.setId(okButton);
                    button.setText("OK");
                    button.setBackgroundResource(num_ok_style_drawable);
                } else if (i == numRow - 1 && j == numCol - 2) {// DEL键
                    button.setId(delButton);
                    button.setBackgroundResource(num_del_style_drawable);
                } else if ((i * numCol + j) < 10) {// 其余按键
                    button.setText(String.valueOf(mRandom[i * numCol + j]));
                    button.setBackgroundResource(num_style_drawable);
                }
                linearlayout.addView(button);
            }
            linear.setPadding(Utils.getScaledValueX(15), Utils.getScaledValueX(20), Utils.getScaledValueX(15),
                    Utils.getScaledValueX(20));
            linear.addView(linearlayout);
        }
    }

    private android.view.View.OnClickListener KeyClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            int hide_id = Utils.getResourcesId(mContext, "hide", "id");
            int numorstr_id = Utils.getResourcesId(mContext, "numorstr", "id");
            int abc123_drawable = Utils.getResourcesId(mContext, "abc123", "drawable");
            int abc_drawable = Utils.getResourcesId(mContext, "abc", "drawable");
            TextView textView = (TextView) mPasswordText.realView_;
            if (v.getId() == hide_id) {
                // 隐藏键盘键
                LPKeyboardView.this.dismiss();
            } else if (v.getId() == numorstr_id) {
                // 数字字母切换
                if (mNumOrStr.equals("num")) {
                    mNumOrStr = "abc";
                    numButton.setBackgroundResource(abc123_drawable);
                } else {
                    mNumOrStr = "num";
                    numButton.setBackgroundResource(abc_drawable);
                }
                initKeyboard();
            } else if (v.getId() == 1000) {
                // 大小写切换
                if (mNumOrStr.equals("abc")) {
                    mNumOrStr = "ABC";
                } else {
                    mNumOrStr = "abc";
                }
                initKeyboard();
            } else if (v.getId() == 1001) {
                // OK键
                LPKeyboardView.this.dismiss();
            } else if (v.getId() == 1002) {
                // DEL键
                if (buttonlist != null && buttonlist.size() != 0) {
                    buttonlist.remove(buttonlist.size() - 1);
                    passwordValue.deleteCharAt(passwordValue.length() - 1);
                    textView.setText(passwordValue.toString().trim());
                    textView.postInvalidate();
                }
            } else {
                if (textView.length() < mMaxSize) {
                    buttonlist.add((LPKeyboardButton) v);
                    passwordValue.append("*");
                }
                textView.setText(passwordValue.toString().trim());
                textView.postInvalidate();
            }

            if (passwordValue != null && passwordValue.length() != 0)
                ((EditText) textView).setSelection(passwordValue.length());

        }

    };

    // 获得随机数字1-9
    private void getRandomNum() {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
        int temp;
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int rnd = Math.abs(random.nextInt()) % 10;
            if (rnd < arr.length) {
                temp = arr[rnd];
                arr[rnd] = arr[0];
                arr[0] = temp;
            }
        }
        mRandom = arr;
    }

    // 获得随机26个小写英文字母
    private void getRandomlittleStr() {
        String temp;
        Random random = new Random();
        for (int i = 0; i < 26; i++) {
            int rnd = Math.abs(random.nextInt()) % 26;
            if (rnd < littleLetter.length) {
                temp = littleLetter[rnd];
                littleLetter[rnd] = littleLetter[0];
                littleLetter[0] = temp;
            }
        }
        mRandomStr = littleLetter;
    }

    // 获得随机26个大写英文字母
    private void getRandomCapitalStr() {
        String temp;
        Random random = new Random();
        for (int i = 0; i < 26; i++) {
            int rnd = Math.abs(random.nextInt()) % 26;
            if (rnd < capitalLetter.length) {
                temp = capitalLetter[rnd];
                capitalLetter[rnd] = capitalLetter[0];
                capitalLetter[0] = temp;
            }
        }
        mRandomStr = capitalLetter;
    }

}
